<template>
  <div class="app-container">
    <!--工具栏-->
    <crudOperation :permission="permission">
      <el-button slot="left" class="filter-item" size="mini" type="primary" @click="adds"
      >批量添加</el-button>
    </crudOperation>
    <div class="head-container">
      <el-dialog v-dialog-drag style="width: 80vm" title="搜索"   close-on-click-modal :visible.sync="crud.props.searchToggle"
                 width="50%">
        <el-form size="small" :model="query" ref="form" :rules="rules" class="formClass" label-width="85px" >
          <el-row :gutter="10">
            <el-col span="12">
              <el-form-item label-width="120px" label="同期开始日期">
                <el-date-picker
                  v-model="query.yoyStartDate"
                  unlink-panels
                  style="width: 80%"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  range-separator=""
                  placeholder="开始日期"
                />
              </el-form-item>
            </el-col>
            <el-col span="12">
              <el-form-item  label-width="120px" label="同期结束日期">
                <el-date-picker
                  v-model="query.yoyEndDate"
                  unlink-panels
                  style="width: 80%"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  range-separator=""
                  placeholder="开始日期"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col span="12">
              <el-form-item label-width="120px" label="前期开始日期">
                <el-date-picker
                  v-model="query.earlyStartDate"
                  unlink-panels
                  style="width: 80%"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  range-separator=""
                  placeholder="开始日期"
                />
              </el-form-item>
            </el-col>
            <el-col span="12">
              <el-form-item  label-width="120px" label="前期结束日期">
                <el-date-picker
                  v-model="query.earlyEndDate"
                  unlink-panels
                  style="width: 80%"
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  default-value
                  range-separator=""
                  placeholder="开始日期"
                />
              </el-form-item>
            </el-col>
          </el-row>


          <el-row :gutter="10">
            <el-col span="12">
              <el-form-item label-width="120px" prop="dateRefer" label="日期参考">
                <el-select v-model="query.dateRefer"
                           style="width: 80%"
                           collapse-tags
                           class="edit-input" placeholder="请选择查询类型" >
                  <el-option label="前期日期" value="1"/>
                  <el-option label="同期日期" value="2"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col span="12">
              <el-form-item label-width="120px" prop="customerId" label="供应商">
                <zSelect :value.sync="query.customerId"
                         style="width: 80%"
                         url="api/dropDown/basCustomerList"
                         :params="{isContact:'1,2'}"
                         />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col span="12">
              <el-form-item label-width="120px" label="商品品牌">
                <zSelect  :value.sync="query.goodsBrandIds"  style="width: 80%"
                         url="api/dropDown/basGoodsBrandList" >
                </zSelect>
              </el-form-item>
            </el-col>
            <el-col span="12">
              <el-form-item label-width="120px"  label="商品名称">
                <table-select
                  :tableColumns="[{prop:'goodsCode',label:'商品编码',width:'100'},{prop:'goodsName',label:'商品名称',width: '280'}]"
                  labelKey="goodsName"
                  valueKey="goodsId"
                  :value.sync="query.goodsIds"
                  placeholder="请选择商品"
                  style="width: 80%"
                  url="/api/dropDown/basGoodsListForAdd"
                ></table-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col span="12">
              <el-form-item  label-width="120px" label="商品分类">
                <treeselect
                  v-model="goodsTypeIds"
                  :options="typeList"
                  placeholder="商品分类"
                  style="width: 80%"
                  :normalizer="normalizer"
                  multiple
                  @input="val=>getNoStr(val,'typeList','goodsTypeIds')"
                />
              </el-form-item>
            </el-col>
            <el-col span="12">
              <el-form-item label-width="120px" prop="stockRefer" label="库存参考">
                <el-select v-model="query.stockRefer"
                           style="width: 80%"
                           collapse-tags
                           class="edit-input" placeholder="请选择查询类型" >
                  <el-option label="现存量" value="1"/>
                  <el-option label="可用量" value="2"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col span="12">
              <el-form-item label-width="120px" prop="isSendWarehouse" label="只计算发货仓">
                <el-select v-model="query.isSendWarehouse"
                           style="width: 80%"
                           collapse-tags
                           class="edit-input" placeholder="请选择" >
                  <el-option label="否" value="0"/>
                  <el-option label="是" value="1"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col span="12">
              <el-form-item  label-width="120px" prop="warehouseId" label="仓库">
                <zSelect :value.sync="query.warehouseId"
                         url="api/dropDown/basWarehouseList"
                         style="width:  80%"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col span="12">
              <el-form-item label-width="120px" prop="isStockControl" label="是否库存控制">
                <el-select v-model="query.isStockControl"
                           style="width: 80%"
                           collapse-tags
                           class="edit-input" placeholder="请选择" >
                  <el-option label="否" value="0"/>
                  <el-option label="是" value="1"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col span="12">
              <el-form-item label-width="120px" label="库存控制类型">
                <el-select v-model="query.StockControlType"
                           style="width: 80%"
                           collapse-tags
                           class="edit-input" placeholder="请选择" >
                  <el-option label="最低库存" value="min"/>
                  <el-option label="最高库存" value="max"/>
                  <el-option label="安全库存" value="safe"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="flex fow-reverse" >
            <el-button class="filter-item"  size="mini" type="primary" @click="queryReport">搜索</el-button>
            <el-button class="filter-item" plain   size="mini" type="primary"
                       @click="resetQuery" >重置</el-button>
          </el-row>
        </el-form>
      </el-dialog>
      <right-click-menu @tableConfig="tableConfig" :options.sync="rightClickMenuConfig"></right-click-menu>
      <!--表格渲染-->
      <el-table ref="table1" border  :data="crud.data" size="small"
                style="width: 100%;"
                @header-dragend="changeColWidth"
                show-summary
                height="400"
                :summary-method="crud.sumRow"
                :row-style="crud.rowClass"
                :row-class-name="rowClassName"
                @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column
          fixed="left"
          label="操作"
          width="60">
          <template slot-scope="{row}">
            <el-button type="text" size="small" @click="addDetail(row)">添加</el-button>
          </template>
        </el-table-column>
        <!-- <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号"/> -->
        <el-table-column :render-header="crud.renderHeader"
        v-for="(item,index) in columnList"
        :key="index"
        :prop="item.prop"
        :label="item.label"/>
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>
    <el-button
      class="filter-item"
      size="mini"
      type="primary"
      @click="save"
      style="margin-bottom: 10px"
      v-permission="permission.addBuyOrder"
    >
     保存
    </el-button>
    <el-table ref="table" border  :data="selectList" size="small"
              style="width: 100%;"
              @header-dragend="changeColWidth"
              show-summary
              v-draghead="manyTableOption"
              height="400"
              :summary-method="crud.sumRow"
              @row-click="crud.selectRow"
              :row-style="crud.rowClass"
              :row-class-name="rowClassName"
              @selection-change="crud.selectionChangeHandler">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="55" label="序号"/>
      <el-table-column :render-header="crud.renderHeader" v-for="(item,index) in columnList" :key="index" :prop="item.prop" :label="item.label">
        <template scope="{row}">
          <span v-if="item.prop === 'curBuyGoodsCount'">
            <el-input
                      oninput="value=value.replace(/[^\d^\.]/g,'')"
                      maxlength="12"
                      @change="curBuyGoodsCount(row)"
                      v-model.lazy="row.curBuyGoodsCount"
                      style="width: 100%"/>
          </span>
          <span v-else-if="item.prop === 'curBuyBoxCount'">
            <el-input
                      oninput="value=value.replace(/[^\d^\.]/g,'')"
                      maxlength="12"
                      @change="curBuyBoxCount(row)"
                      v-model.lazy="row.curBuyBoxCount"
                      style="width: 100%"/>
          </span>
          <span v-else-if="item.prop === 'buyPrice'">
            <el-input
                      oninput="value=value.replace(/[^\d^\.]/g,'')"
                      maxlength="12"
                      v-model.lazy="row.buyPrice"
                      style="width: 100%"/>
          </span>
          <span v-else>
            {{ row[item.prop] }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="100">
        <template slot-scope="{$index}">
          <el-button type="text"  @click="delDetail($index)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import crudBuyAnalysis from '@/api/erp/buyAnalysis'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import Treeselect from '@riophae/vue-treeselect'
import {get} from '@/api/erp/reportCustomerFee'
import { publicListKey } from "@/utils/key";
import {tablemixins} from "@/mixins/tablemixins";
import  jTableColumnConfig  from "@/components/jTableColumnConfig/jTableColumnConfig";
import tableSelect from '@/components/tableSelect/tableSelect'
import { basSubjectDropDownTree } from '@/api/erp/basSubject'
import { manyTableMixin } from '../../../mixins/manyTableMixin'
import { basGoodsTypeTree } from '../../../api/erp/basGoods'
import { addBuyOrder } from '../../../api/erp/buyAnalysis'


// crud交由presenter持有
const defaultCrud = CRUD({ title: '采购分析',
  optShow: {
    add: false,
    edit: false,
    del: false,
    download: true,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: false,
    reject: false,
    invalid: false,
    recover: false,
    downloadDetail: false,
    print: false,
    printDetail: false
  },
  queryOnPresenterCreated:false,
  url: 'api/buyAnalysis', sort: '',
  crudMethod: { ...crudBuyAnalysis }})
const defaultForm = { queryType: null, startDate: null, endDate:null}
export default {
  name: 'buyAnalysis',
  components: { pagination, crudOperation, rrOperation, udOperation,Treeselect,jTableColumnConfig, tableSelect },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(),publicListKey, manyTableMixin],
  dicts:[],
  mounted(){
    this.crud.props.searchToggle = true
  },
  created() {
    this.$set(this.query,'dateRefer','1')
    this.$set(this.query,'stockRefer','1')
    this.$set(this.query,'isSendWarehouse','0')
    this.$set(this.query,'isStockControl','0')
    this.$set(this.query,'StockControlType','min')
    const date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth()+1
    const day = date.getDate()
    const earlyStartDate = month === 1?`${year-1}-12-${day}`:`${year}-${month-1}-${day}`
    const yoyStartDate = month === 1?`${year-2}-12-${day}`:`${year-1}-${month-1}-${day}`
    this.$set(this.query,'yoyStartDate',yoyStartDate)
    this.$set(this.query,'yoyEndDate',`${year-1}-${month}-${day}`)
    this.$set(this.query,'earlyStartDate',earlyStartDate)
    this.$set(this.query,'earlyEndDate',`${year}-${month}-${day}`)
    basGoodsTypeTree().then(res=>{
      this.typeList = res
    })
  },
  data() {
    return {
      subjectIds:[],
      goodsTypeIds:[],
      typeList:[],
      subjectList: [],
      columnList:[
        {label:'费用合同单号',prop:'feeContractCode'},
        {label:'费用合同名称',prop:'feeContractName'},
        {label:'商品编码',prop:'goodsCode'},
        {label:'商品名称',prop:'goodsName'},
        {label:'条形码',prop:'barcode'},
        {label:'商品分类',prop:'goodsTypeName'},
        {label:'商品品牌',prop:'goodsBrandName'},
        {label:'箱装量',prop:'boxUnitCount'},
        {label:'实际数量',prop:'actualGoodsCount'},
        {label:'实际箱数',prop:'actualBoxCount'},
        {label:'实际金额',prop:'actualAmount'},
        {label:'可用量',prop:'usableNum'},
        {label:'可用箱数',prop:'usableBoxCount'},
        {label:'可用金额',prop:'usableAmount'},
        {label:'在途量',prop:'onWayNum'},
        {label:'在途箱数',prop:'onWayBoxCount'},
        {label:'在途金额',prop:'onWayAmount'},
        {label:'同期销售数量',prop:'yoySaleGoodsCount'},
        {label:'同期销售箱数',prop:'yoySaleBoxCount'},
        {label:'同期销售金额',prop:'yoySaleAmount'},
        {label:'前期销售数量',prop:'earlySaleGoodsCount'},
        {label:'前期销售箱数',prop:'earlySaleBoxCount'},
        {label:'前期销售金额',prop:'earlySaleAmount'},
        {label:'可订数量',prop:'canBuyGoodsCount'},
        {label:'可订箱数',prop:'canBuyBoxCount'},
        {label:'采购价',prop:'buyPrice'},
        {label:'采购协议价',prop:'buyProtocolPrice'},
        {label:'本次订购数量',prop:'curBuyGoodsCount'},
        {label:'本次订购箱数',prop:'curBuyBoxCount'},
        {label:'本次订购金额',prop:'curBuyAmount'},
        {label:'订购后数量',prop:'afterBuyGoodsCount'},
        {label:'订购后箱数',prop:'afterBuyBoxCount'},
        {label:'订购后金额',prop:'afterBuyAmount'},
      ],
      selectList:[],

      queryType:'',
      initialRightEvent: [
      ],
      extendRightEvent:[
        {
          fnHandler: 'delDetail', // 绑定事件
          icoName: 'el-icon-delete', // icon图标
          btnName: '删除' // 菜单名称
        },
      ],
      permission: {
        export: ['admin', 'buyAnalysis:export'],
        addBuyOrder: ['admin', 'buyAnalysis:addBuyOrder']
      },
      rules: {
        stockRefer: [
          { required: true, message: '库存参考不能为空', trigger: 'blur' },
        ],
        warehouseId: [
          { required: true, message: '仓库不能为空', trigger: 'blur' },
        ],
        isStockControl: [
          { required: true, message: '是否库存控制不能为空', trigger: 'blur' },
        ],
        customerId: [
          { required: true, message: '供应商不能为空', trigger: 'blur' },
        ],
        isSendWarehouse: [
          { required: true, message: '是否只计算发货仓不能为空', trigger: 'blur' },
        ],
      },
      subjectFeeList:[],
    }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table1.doLayout()
      this.$refs.table.doLayout()
    })
  },
  watch: {
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    adds(){
      const selections=this.$refs['table1'].selection
      for (let i = 0; i < selections.length; i++) {
        this.addDetail(selections[i])
        // // 可订数量不为0
        // if (selections[i].canBuyGoodsCount!==0) {
        //   // 下面表格没有数据
        //   if (this.selectList.length===0) {
        //     selections[i].curBuyGoodsCount=selections[i].canBuyGoodsCount
        //     selections[i].curBuyBoxCount=selections[i].canBuyBoxCount
        //     this.selectList.push(Object.assign({},selections[i]))
        //   }else{
        //   for (let a = 0; a < this.selectList.length; a++) {
        //     if (this.selectList[a].goodsId!==selections[i].goodsId) {
        //       // 下面表格有数据没有添加过本条数据
        //       selections[i].curBuyGoodsCount=selections[i].canBuyGoodsCount
        //       selections[i].curBuyBoxCount=selections[i].canBuyBoxCount
        //       this.selectList.push(Object.assign({},selections[i]))
        //     }
        // }
        // }
        // }
       }
    },
    rowClassName({row, rowIndex}){
      if(row.buyProtocolPrice&&!row.buyProtocolPrice==''){
        return 'bgcred'
      }
    },
    queryReport(){
      this.$refs['form'].validate((valid) => {
        if (valid){
          if (this.query.dateRefer === '1'){
            if(!this.query.yoyStartDate || !this.query.yoyStartDate)return this.$message.error('同期日期不能为空')
          }else {
            if(!this.query.earlyStartDate || !this.query.earlyEndDate)return this.$message.error('前期日期不能为空')
          }
          this.crud.props.searchToggle = false
          this.crud.toQuery()
        }
      })
      // this.init()
      // this.crud.toQuery()
      // this.crud.props.searchToggle = false
    },
    // addDetail(row){
    //   console.log(row[row.length-1]);
    //   const rows=row[row.length-1]
    //     const index = this.selectList.findIndex(item=>item.goodsId === rows.goodsId)
    //   if (~index){
    //     this.$message.error('已添加')
    //   }else {
    //     if(rows.canBuyGoodsCount === 0)return this.$message.success('可订数量为0')
    //     this.selectList.push(Object.assign({},rows))
    //   }
    // },
    addDetail(row){
      const index = this.selectList.findIndex(item=>item.goodsId === row.goodsId)
      if (~index){
        this.$message.error('已添加')
      }else {
        if(row.canBuyGoodsCount === 0)return this.$message.success(`${row.goodsName}可订数量为0`)
        row.curBuyGoodsCount=row.canBuyGoodsCount
        row.curBuyBoxCount=row.canBuyBoxCount
        this.selectList.push(Object.assign({},row))
      }
    },
    delDetail(index){
      this.selectList.splice(index,1)

    },
    curBuyGoodsCount(row){
      if (row.curBuyGoodsCount > row.canBuyGoodsCount)row.curBuyGoodsCount=row.canBuyGoodsCount
    },
    curBuyBoxCount(row){
      if (row.curBuyBoxCount > row.canBuyBoxCount)row.curBuyBoxCount=row.canBuyBoxCount
    },
    getIdCodeList(row,type){
      if(row.orderId || row.loanIds){
        const idList = type===1? row.orderId.split(",") : row.loanIds.split(",");
        const codeList = type===1? row.orderCode.split(",") : row.loanCode.split(",");
        const lst = []
        idList.forEach(function (id, index) {
          lst.push({"id":id,"code":codeList[index]})
        })
        return lst;
      }
    },
    getNoStr(val,type,prop){
      let str = ''
      val.forEach(item=>{
        const itemNode = this.getTreeName1(this[type],item)
        str = this.getNode(itemNode,str)
      })
      this.query[prop] = str
    },
    getTreeName1(treeList,id){
      let _this=this
      for (let i = 0; i < treeList.length; i++) {
        let treeItem=treeList[i]
        if(treeItem.id===id){
          return treeItem
        }else{
          if(treeItem.children && treeItem.children.length>0){
            let res=_this.getTreeName1(treeItem.children,id)
            if(res){
              return res
            }
          }
        }
      }
    },
    getNode(node,str){
      if (node.children){
        for (let i =0;i<node.children.length;i++){
          str = this.getNode(node.children[i],str)
        }
      }
      return str+=node.id+ ','
    },
    save(){
      if(!this.selectList.every(item=>item.curBuyGoodsCount))return this.$message.error('请先输入订购数量')
      const data = {
        customerId:this.query.customerId,
        warehouseId: this.query.warehouseId,
        detailList: this.selectList
      }
      addBuyOrder(data).then(res=>{
        if (res.status === 200){
          this.selectList = []
          this.$message.success(res.msg)
          this.crud.refresh()
        }else {
          this.$message.error(res.msg)
        }
      }).catch(err=>{
        this.$message.error(err.msg)
      })
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    jumpDetail(id,type){
      let path = '/fee/feeOrderDetail/'
      this.$router.push({path:`${path}${id}`})
    },
  }
}
</script>

<style lang="scss" scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
.flex{
  display: flex;
}
.fow-reverse{
  flex-direction: row-reverse;
}
.codeJump{
  background-image:-webkit-linear-gradient(top,yellow,#ff00fb);
  -webkit-background-clip:text;
  -webkit-text-fill-color:transparent;
  cursor: pointer;
}
</style>
